<script setup lang="ts">
import { onMounted } from 'vue';
import dayjs from 'dayjs';
import { navigateTo, getCurrentInstance } from '@tarojs/taro';
import { IconFont as NutIconIconFont } from '@nutui/icons-vue-taro';
import { APP_KNOWLEDGE_LIST_QUERY } from '/@/api/modules/base/knowledge';
import { state } from './state';

/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as {
  id: string;
};

/**
 * @description 文章列表查询
 * @param {Number} page -当前页
 * @param {Number} pageSize -每页条数
 */
function queryList(page: number = 1, pageSize: number = 15) {
  if (!page && state.finished) return;
  state.loading = true;

  APP_KNOWLEDGE_LIST_QUERY({
    comQuery: { page, pageSize },
    knowledgeDto: { baseTypeId: params.id },
  })
    .then((res) => {
      state.loading = false;

      if (
        state.activePage >=
        (res.comQuery.pageCount ||
          (res.comQuery.totalCount as number) / (res.comQuery.pageSize as number) ||
          1)
      )
        state.finished = true;
      if (!res.knowledgeDto || !res.knowledgeDto.length) return;
      state.list.push(...res.knowledgeDto);
      state.activePage += 1;
    })
    .catch(() => {
      state.loading = false;
    });
}

/**
 * @function 加载
 */
function onLoading() {
  if (state.finished) return;

  queryList(state.activePage);
}

onMounted(() => {
  state.activePage = 1;
  state.loading = true;
  state.finished = false;
  state.list = [];
  onLoading();
});
</script>
<template>
  <view class="knowledge-list app-page--1">
    <app-navbar title="文章列表" />
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="knowledge-list__wrapper">
        <view
          class="knowledge-item"
          v-for="item in state.list"
          @click="
            navigateTo({
              url: `/pages/knowledge/detail/index?id=${item.id}`,
            })
          "
        >
          <view class="knowledge-item__header">
            <view class="knowledge-item__header--left">{{ item.baseTitle }}</view>
            <view class="knowledge-item__header--right">
              <nut-icon-icon-font name="message" /><span>{{ item.viewNumber }}</span>
            </view>
          </view>
          <view class="knowledge-item__time"
            >{{ dayjs(Number(item.createTime)).format('YYYY-MM-DD') }}
          </view>
        </view>
      </view>
      <view class="app-page__list-tips">
        <text v-if="!state.list.length">暂无数据！</text>
        <text v-else-if="state.list.length && state.loading">加载中...</text>
        <text v-else-if="state.list.length && state.finished">加载完成!</text>
      </view>
    </scroll-view>
  </view>
</template>
<style lang="scss" scoped>
@import './index.scss';
</style>
